<?php
namespace Admin\Controller;
use Think\AjaxPage;
use Think\AjaxPage2;
use Admin\Logic\GoodsLogic;
use Think\Page;

class PromotionController extends BaseController {

    public function index(){
        $this->display();
    }
	//转盘列表
	public function zp_list()
	{
		$keywords=I('keywords'); $status=I('status',0);
		$parse_type = array('0'=>'单品秒杀','1'=>'降价促销','2'=>'一口价促销','3'=>'买就赠优惠券','4'=>'全店打折');
		$level = M('user_level')->select();
		if($level){
			foreach ($level as $v){
				$lv[$v['level_id']] = $v['level_name'];
			}
		}
		$this->assign("parse_type",$parse_type);

		$where='a.id=a.id ';

		if($keywords)
		$where.=' and (b.company like "%'.$keywords.'%" or b.mobile like "%'.$keywords.'%")';


		$count = M('zhuanpan_log a')->field('a.*,b.zp_cishu,b.company,b.nickname,b.mobile')->join('ty_users b on a.user_id=b.user_id','LEFT')->where($where)->count();
		$Page  = new \Think\Page($count,50);
		$show = $Page->show();
		$res = M('zhuanpan_log a')->field('a.*,b.zp_cishu,b.company,b.nickname,b.mobile')->join('ty_users b on a.user_id=b.user_id','LEFT')->where($where)->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();

		if($res){
			foreach ($res as $key=>$val){
				$res[$key]['state'] = empty($val['status']) ? '<span style="color:red">待审核</span>' : '<span style="color:green">已审核</span>';
			}
		}
	    $this->assign('page',$show);// 赋值分页输出
		$this->assign('prom_list',$res);
		$this->display();
	}
	public function ajaxdaily_goods_list(){
	    $parse_type = array('0'=>'单品秒杀','1'=>'降价促销','2'=>'一口价促销','3'=>'买就赠优惠券','4'=>'全店打折',5=>'每日秒杀');
        $keywords = I('keywords');
        $where = '1=1';
        if(!empty($keywords)){
            $where = 'a.name like "%'.$keywords.'%" or b.store_name like "%'.$keywords.'%"';
        }
        $where .= ' and a.type = 5';
        $level = M('user_level')->select();
        if($level){
            foreach ($level as $v){
                $lv[$v['level_id']] = $v['level_name'];
            }
        }
        $this->assign("parse_type",$parse_type);
        $count = M('prom_goods a')
            ->field('a.*,b.store_name')
            ->join('ty_store b on a.store_id=b.store_id','LEFT')
            ->where($where)
            ->count();
        // $Page  = new \Think\Page($count,10);
        $Page  = new AjaxPage($count,20);
        $show = $Page->show();
        $res = M('prom_goods a')
            ->field('a.*,b.store_name,b.zhekou')
            ->join('ty_store b on a.store_id=b.store_id','LEFT')
            ->where($where)
            ->order('a.id desc')
            ->limit($Page->firstRow.','.$Page->listRows)
            ->select();
        //       $count = M('prom_goods')->where("store_id=".$this->store_id)->count();
        //       $Page  = new \Think\Page($count,10);
        //       $show = $Page->show();
        // $res = M('prom_goods')->where("store_id=".$this->store_id)->limit($Page->firstRow.','.$Page->listRows)->select();
        if($res){
            foreach ($res as $val){
                if(!empty($val['group']) && !empty($lv)){
                    $val['group'] = explode(',', $val['group']);
                    foreach ($val['group'] as $v){
                        $val['group_name'] .= $lv[$v].',';
                    }
                }
                $val['state'] = empty($val['status']) ? '管理员关闭' : '正常';
                if($val['end_time']<time()){
                    $val['state'] = '已结束';
                }
                $prom_list[] = $val;
            }
        }
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('prom_list',$prom_list);
        $this->display();
	}
    /**
     * 每日秒杀
     * */
    public function daily_goods_list(){
        $this->display();
    }
    
	public function huodongguolv(){ //活动过滤
	    set_time_limit(0);
		$action=I('action');
		$keywords=I('keywords');
	    $timegap = I('timegap');
	    if($timegap){
	    	$gap = explode(' - ', $timegap);
	    	$begin = strtotime($gap[0]);
	    	$end = strtotime($gap[1]);
			$this->assign('timegap',$gap[0].' - '.$gap[1]);
	    }else{
			$begin = date('Y-m-d 00:00',(time()-10*60*60*24));//30天前
			$end = date('Y-m-d 23:59',strtotime('+1 days'));
			$this->assign('timegap',$begin.' - '.$end);
			$begin = strtotime($begin);
	    	$end = strtotime($end);
		}
		$wheres='';
		if($keywords){
			$keys=\explode(',',$keywords);
			foreach($keys as $vs){
				$wheres.=' and a.goods_name not like "%'.$vs.'%" ';
			}
		}else{
			$keywords='电线,电缆,铁钉,铁线';
		}

	  $where='add_time>'.$begin.' and add_time<'.$end.$wheres.' and b.order_status<3';
        
	   	$order_list=M('order_goods a')
		->field('a.goods_name,order_amount,b.user_id')
		->join('ty_order b on a.order_id=b.order_id','LEFT')
		->where($where)
		->group('b.order_id')
		->select();
	   	
		$result = [];
		foreach ($order_list as $item) {
		    if (!isset($result[$item["user_id"]])) {
		        $result[$item["user_id"]] = 0;
		    }
		    $result[$item["user_id"]] = bcadd($result[$item["user_id"]],$item["order_amount"],3);
		}
		
		$users=M('order_goods a')
		->field('b.user_id,c.fenbu_id,c.company,c.biaoshi_xian,c.fenbu_id,c.mobile')
		->join('ty_order b on a.order_id=b.order_id','LEFT')
		->join('ty_users c on b.user_id=c.user_id')
		->where($where)
		->group('b.user_id')
		->select();

		$fenbu_data = M('fenbu')->field('fenbu_id,fenbu_name')->select();
		$fb_data = [];
		foreach($fenbu_data as $fkey=>$fvs){
		    $fb_data[$fvs['fenbu_id']] = $fvs['fenbu_name'];
		}
		
		$data=[];
		foreach($users as $key=>$vs){
			$data[$key]=$vs;
			$data[$key]['fenbu_name']=$fb_data[$vs['fenbu_id']];
			//$data[$key]['fenbu_name']=M('fenbu')->where('fenbu_id='.$vs['fenbu_id'])->getField('fenbu_name');
			$ujine=0;
			if(isset($result[$vs['user_id']])){
			    $ujine+=$result[$vs['user_id']];
			}
// 			foreach($order_list as $v){
// 				if($vs['user_id']==$v['user_id']){
// 					$ujine+=$v['order_amount'];
// 				}
// 			}

			$data[$key]['order_amount']=$ujine;
		}

		$all_num = array_column($data,'order_amount');
		array_multisort($all_num,SORT_DESC,$data);
	  	$data=array_splice($data,0,199);

		if($action=='daochu'){
		$strTable ='<table width="500" border="1">';
		$strTable .= '<tr>';
		$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">分部</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">线路</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">下单客户</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">客户电话</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">消费金额</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">下单时间</td>';

		foreach($data as $vs){
				$strTable .= '<tr>';
				$strTable .= '<td style="text-align:center;font-size:12px;">'.$vs['fenbu_name'].'</td>';
				$strTable .= '<td style="text-align:center;font-size:12px;">'.$vs['biaoshi_xian'].'</td>';
				$strTable .= '<td style="text-align:center;font-size:12px;">'.$vs['company'].'</td>';
				$strTable .= '<td style="text-align:center;font-size:12px;">'.$vs['mobile'].'</td>';
				$strTable .= '<td style="text-align:center;font-size:12px;">'.$vs['order_amount'].'</td>';
				$strTable .= '<td style="text-align:center;font-size:12px;">'.date('Y-m-d H:i',$begin).' - '.date('Y-m-d H:i',$end).'</td>';
				$strTable .= '</tr>';
				}

			$strTable .='</table>';
			unset($order_list);
			downloadExcel($strTable,'order');
			exit();
		}
	$this->assign('keywords',$keywords);
	$this->assign('data',$data);
	$this->display();
	    }
 /**
     *  折扣分部修改
     */
     public function fenbustore(){
         $store_id = I('store_id');
         if(empty($store_id)){
             die;
         }
         $time = time();
         $prom_goods = M('prom_goods')->where("start_time <$time and end_time > $time and store_id = $store_id and zd=1")->find();
         if(empty($prom_goods)){
             $this->error("没有正在进行的全店打折");
             die;
         }
         if(!empty($prom_goods['fenbu_expression'])){
             $prom_goods['fenbu_expression'] = json_decode($prom_goods['fenbu_expression'],true);
         }
      ;
         $fenbu = M('fenbu')->select();
         foreach ($fenbu as $k=>$v){
            $fenbu[$k]['fenbu_id'] = $v['fenbu_id'];
            $fenbu[$k]['fenbuexpression'] = '';
            if(!empty($prom_goods['fenbu_expression'])){
               foreach ($prom_goods['fenbu_expression'] as $key=>$val){
                    if($val['fenbu_id'] == $v['fenbu_id']){
                        $fenbu[$k]['fenbuexpression'] = $val['fenbuexpression'];
                    }
                } 
            }
            
         }
         if(IS_POST){
             $fenbu_id = I('fenbu_id');
             $fenbuexpression = I('fenbuexpression');
             $store_id = I('store_id');
         
             $fenbuarr = [];
             foreach ($fenbu_id as $k=>$v){
                 if(!empty($fenbuexpression[$k])){
                     $fenbuarr[$k]['fenbu_id'] = $v;
                    $fenbuarr[$k]['fenbuexpression'] = $fenbuexpression[$k];
                 }
                 
                //  
                //  M('fenbu_goods')->where(['fenbu_id'=>$k,'goods_id'=>$goods_id])->save(['sales_sum'=>$v,'sorts'=>$sorts[$k]]);
             }
             sort($fenbuarr);
             $json = json_encode($fenbuarr);
           
             M('prom_goods')->where("start_time <$time and end_time > $time and store_id = $store_id and zd=1")->save(['fenbu_expression'=>$json]);
             $this->success("操作成功!!!",U('Admin/Promotion/fenbuStore?store_id='.$store_id));
             die;
         }
        //  dump($fenbu);
        $this->assign('fenbu',$fenbu);
        $this->display();  
     }
	//活动报名列表
	public function join_goods_list()
	{
		$keywords=I('keywords'); $status=I('status',0);
		$parse_type = array('0'=>'单品秒杀','1'=>'降价促销','2'=>'一口价促销','3'=>'买就赠优惠券','4'=>'全店打折');
		$level = M('user_level')->select();
		if($level){
			foreach ($level as $v){
				$lv[$v['level_id']] = $v['level_name'];
			}
		}
		$this->assign("parse_type",$parse_type);

		$where='a.id=a.id ';

		if($keywords)
		$where.=' and b.store_name like "%'.$keywords.'%"';

		$where.=' and a.status='.$status;
		$count = M('goods_join a')->field('a.*,b.store_name')->join('ty_store b on a.store_id=b.store_id','LEFT')->where($where)->count();
		$Page  = new \Think\Page($count,10);
		$show = $Page->show();
		$res = M('goods_join a')->field('a.*,b.store_name')->join('ty_store b on a.store_id=b.store_id','LEFT')->where($where)->order('id asc')->limit($Page->firstRow.','.$Page->listRows)->select();

		if($res){
			foreach ($res as $key=>$val){
				$res[$key]['state'] = empty($val['status']) ? '<span style="color:red">待审核</span>' : '<span style="color:green">已审核</span>';
				// if($val['end_time']<time()){
				// 	$res[$key]['state'] = '已结束';
				// }
			}
		}
        $this->assign('page',$show);// 赋值分页输出
		$this->assign('prom_list',$res);
		$this->display();
	}
	public function join_goods_info()
	{
		$this->assign('min_date',date('Y-m-d'));
		$level = M('user_level')->select();
		$this->assign('level',$level);
		$prom_id = I('id');
		$info['start_time'] = date('Y-m-d');
		$info['end_time'] = date('Y-m-d',time()+3600*60*24);
		if($prom_id>0){
			$info = M('goods_join')->where("id=$prom_id")->find();
			if(empty($info))
				$this->error('非法操作！');

			$info['start_time'] = date('Y-m-d',$info['start_time']);
			$info['end_time'] = date('Y-m-d',$info['end_time']);
			if($info['goods_key']){
				$goods_key=\json_decode($info['goods_key']);
				foreach($goods_key as $key=>$v){
					$prom_goods[$key]= M('spec_goods_price a')->field('a.key,a.key_name,a.price,b.*')->join('ty_goods b on a.goods_id=b.goods_id','LEFT')->where('a.key="'.$v.'"')->find();
					$prom_goods[$key]['shop_price']=$prom_goods[$key]['price'];
				}

			}else{
				$prom_goods = M('goods')->where("prom_id=$prom_id")->select();
			}

			$this->assign('prom_goods',$prom_goods);
		}
		$this->assign('info',$info);
		$this->assign('min_date',date('Y-m-d'));
		$this->initEditor();
		$this->display();
	}

	public function join_goods_save()
	{
		$prom_id = I('id');
		$data = I('post.');
		$data['start_time'] = strtotime($data['start_time']);
		$data['end_time'] = strtotime($data['end_time']);
		$data['goods_key'] = \json_encode($data['goods_key']);
		$goods_join=M('goods_join')->where('id='.$prom_id)->find();
		if($data['prom_type']==4){
			$data['zd']=1;
		}

		if($prom_id){
			M('goods_join')->where("id=$prom_id and store_id =".$goods_join['store_id'])->save($data);
			$last_id = $prom_id;
			adminLog("管理员修改了商品促销 ".I('name'));
		}else{
			// $last_id = M('goods_join')->add($data);
			// sellerLog("管理员添加了商品促销 ".I('name'));
		}
		$this->success('编辑促销活动成功',U('Promotion/join_goods_list'));
	}

	public function join_goods_del()
	{
		$prom_id = I('id');
		M('goods_join')->where("id=$prom_id")->delete();
		$this->success('删除活动成功',U('Promotion/prom_goods_list'));
	}
	public function join_get_goods(){
		$prom_id = I('id');
		$goods_join=M('goods_join')->where('id='.$prom_id)->find();
		$parse_type = array('0'=>'单品秒杀 %','1'=>'降价促销 元','2'=>'一口价促销 元','3'=>'买就赠优惠券','4'=>'全店打折 %');
		$this->assign("parse_type",$parse_type);

		if($goods_join['zd']){
			$count =M('goods')->where("store_id=".$goods_join['store_id'])->count();
			$goodsList = M('goods')->where("store_id=".$goods_join['store_id'])->order('goods_id DESC')->select();
			foreach($goodsList as $key=>$v){
				$goodsList[$key]['key_name']='全规格';
				$goodsList[$key]['price']=$v['shop_price'];
				$goodsList[$key]['xiangou']=$goods_join['xiangou'];
				$goodsList[$key]['expression']=$goods_join['expression'];
				$goodsList[$key]['prom_type']=$goods_join['prom_type'];
			}
		}else{
			$goods_key=\json_decode($goods_join['goods_key']);
			foreach($goods_key as $key=>$v){
				$goodsList[$key]= M('spec_goods_price a')->field('a.*,b.goods_name')->join('ty_goods b on a.goods_id=b.goods_id','LEFT')->where('a.key="'.$v.'"')->find();
				$goodsList[$key]['xiangou']=$goods_join['xiangou'];
				$goodsList[$key]['expression']=$goods_join['expression'];
				$goodsList[$key]['prom_type']=$goods_join['prom_type'];
			}
		}
		$Page  = new \Think\Page($count,10);
		$show = $Page->show();
		$this->assign('page',$show);
		$this->assign('goodsList',$goodsList);
		$this->display();
	}


        /**
         * 店铺活动列表
         */
	public function prom_store_list()
	{
                
            // dump($prom_time);
		$store_name = I('store_name');
        $create_time = I('store_time');
		$zhekou = I('zhekou');
		$store_id=I('store_id');
		$start_time=strtotime(I('start_time'));
		$end_time=strtotime(I('end_time'));
            
            // dump($prom_time);
		if(I('action')=='zhekou' && !empty($store_id)){
			//更新store表
			M('store')->where('store_id='.$store_id)->save(['zhekou'=>$zhekou]);
            $promGoods = M('prom_goods')->where('store_id='.$store_id.' and zd=1')->find();
			$prom_goods=array();
			M('goods')->where('store_id='.$store_id.' and zd=1 and prom_lock=0 ')->save(['prom_type'=>'0','prom_id'=>'0','zd'=>'0']); //清理整店折扣产品
            //过期活动自动改为全店打折
            $time = time();
            $prom_time = M('goods a')
            ->join('ty_prom_goods s on a.prom_id = s.id','LEFT')
            ->where('a.prom_id != 0 and s.start_time<'.$time.' and end_time<'.$time.' and a.store_id='.$store_id)
            ->select();
            foreach ($prom_time as $v){
                M('goods')->where('goods_id='.$v['goods_id'])->save([
						'prom_type'=>'0',
						'zd'=>1,
						'prom_id'=>0
					]);
            }
            
			if($zhekou=='100'){ //不是折扣取消所有数据
				M('prom_goods')->where('store_id='.$store_id.' and zd=1')->delete();

			}else{ //是折扣添加数据

			$store=M('store')->where('store_id='.$store_id.' and store_state=1')->find(); //获取店铺所有产品
			M('prom_goods')->where('store_id='.$store_id.' and zd=1')->delete(); //删除活动数据

			$prom_id=M('prom_goods')->add([
						'name'=>$store['store_name'].'整店促销！',
						'expression'=>$zhekou,
						'description'=>'&lt;p&gt;'.$store['store_name'].'整店促销！&lt;/p&gt;',
						'start_time'=>$start_time,
						'end_time'=>$end_time,
						//'type'=>'4',
						'status'=>'1',
						'group'=>'1',
						'zd'=>1,
						'store_id'=>$store_id,
						'fenbu_expression'=>$promGoods['fenbu_expression'],
					]);echo $prom_id;

				M('goods')->where('store_id='.$store_id.' and prom_id=0 and prom_lock=0')->save([
						'prom_type'=>'0',
						'zd'=>1,
						'prom_id'=>$prom_id
					]);//更新产品折扣
			}

			exit;
		}

		if((!empty(I('zhekou_start_time')) || !empty(I('zhekou_end_time'))) && !empty($store_id)){
			if(!empty(I('zhekou_start_time'))){
				M('prom_goods')->where('store_id='.$store_id.' and zd=1')->save([
						'start_time'=>strtotime(I('zhekou_start_time'))
					]);//更新产品折扣
			}elseif(!empty(I('zhekou_end_time'))){
				M('prom_goods')->where('store_id='.$store_id.' and zd=1')->save([
						'end_time'=>strtotime(I('zhekou_end_time'))
					]);//更新产品折扣
			}
			exit;
		}

        $create_time = str_replace("+"," ",$create_time);
        $create_time2 = $create_time  ? $create_time  : date('Y-m-d',strtotime('-1 year')).' - '.date('Y-m-d',strtotime('+1 day'));
        $create_time3 = explode(' - ',$create_time2);
       // $where['store_time'] =  array(array('gt', strtotime($create_time3[0]), array('lt', strtotime($create_time3[1]))));
        $store_name && $where['store_name'] = array('like','%'.$store_name.'%');
		//$where['zd']=1;

		$count = M("store")->where($where)->count();

        $Page  = new Page($count,15);
		$list = M("store")->where($where)->order('store_money desc')->limit($Page->firstRow.','.$Page->listRows)->select();//\print_r(\json_encode($list));
		foreach($list as $key=>$v){
			$list[$key]['goods_count']=M('goods')->where('store_id='.$v['store_id'])->count();
			$list[$key]['prom_count']=M('prom_goods')->where('store_id='.$v['store_id'])->count();

			$newdate=M('prom_goods')->where('store_id='.$v['store_id'].' and zd=1')->order('id desc')->find();
			$list[$key]['start_time']=$newdate['start_time'];
			$list[$key]['end_time']=$newdate['end_time'];
		}

        $this->assign('create_time',$create_time2);
        $show  = $Page->show();
        $this->assign('show',$show);
        $this->assign('list',$list);
        C('TOKEN_ON',false);
        $this->display();
	}


        /**
         * 商品活动列表
         */
	public function prom_goods_list()
	{
		$parse_type = array('0'=>'单品秒杀','1'=>'降价促销','2'=>'一口价促销','3'=>'买就赠优惠券','4'=>'全店打折');
		$store_name=trim(I('keywords'));
		$level = M('user_level')->select();
		if($level){
			foreach ($level as $v){
				$lv[$v['level_id']] = $v['level_name'];
			}
		}
		$this->assign("parse_type",$parse_type);

		$map=array();
		if($store_name){
			$map['b.store_name|a.name']=array('like', '%'.$store_name.'%');
		}

        $count = M('prom_goods a')->field('a.*,b.store_name')->join('ty_store b on a.store_id=b.store_id','LEFT')->count();
        $Page  = new \Think\Page($count,10);
        $show = $Page->show();
		$res = M('prom_goods a')->field('a.*,b.store_name,b.zhekou')->join('ty_store b on a.store_id=b.store_id','LEFT')->where($map)->limit($Page->firstRow.','.$Page->listRows)->select();

		if($res){
			foreach ($res as $val){
				if(!empty($val['group']) && !empty($lv)){
					$val['group'] = explode(',', $val['group']);
					foreach ($val['group'] as $v){
						$val['group_name'] .= $lv[$v].',';
					}
				}
				$val['state'] = empty($val['status']) ? '管理员关闭' : '正常';
				if($val['end_time']<time()){
					$val['state'] = '已结束';
				}
				$prom_list[] = $val;
			}
		}
                $this->assign('page',$show);// 赋值分页输出
		$this->assign('prom_list',$prom_list);
		$this->display();
	}

	public function prom_goods_info()
	{
		$this->assign('min_date',date('Y-m-d'));
		$level = M('user_level')->select();
		$this->assign('level',$level);
		$prom_id = I('id');
		$info['start_time'] = date('Y-m-d');
		$info['end_time'] = date('Y-m-d',time()+3600*60*24);
		if($prom_id>0){
			$info = M('prom_goods')->where("id=$prom_id")->find();
			$info['start_time'] = date('Y-m-d',$info['start_time']);
			$info['end_time'] = date('Y-m-d',$info['end_time']);
			$prom_goods = M('goods')->where("prom_id=$prom_id and prom_type=3")->select();
			$this->assign('prom_goods',$prom_goods);
		}
		$this->assign('info',$info);
		$this->assign('min_date',date('Y-m-d'));
		$this->initEditor();
		$this->display();
	}

	public function prom_goods_save()
	{
		$prom_id = I('id');
		$data = I('post.');
		$data['start_time'] = strtotime($data['start_time']);
		$data['end_time'] = strtotime($data['end_time']);
		$data['group'] = implode(',', $data['group']);
		if($prom_id){
			M('prom_goods')->where("id=$prom_id")->save($data);
			$last_id = $prom_id;
			adminLog("管理员修改了商品促销 ".I('name'));
		}else{
			$last_id = M('prom_goods')->add($data);
			adminLog("管理员添加了商品促销 ".I('name'));
		}

		if(is_array($data['goods_id'])){
			$goods_id = implode(',', $data['goods_id']);
			if($prom_id>0){
				M("goods")->where("prom_id=$prom_id and prom_type=3")->save(array('prom_id'=>0,'prom_type'=>0,'zd'=>0));
			}
			M("goods")->where("goods_id in($goods_id)")->save(array('prom_id'=>$last_id,'prom_type'=>3,'zd'=>0));
		}
		$this->success('编辑促销活动成功',U('Promotion/prom_goods_list'));
	}

	public function prom_goods_del()
	{
		$prom_id = I('id');
                $order_goods = M('order_goods')->where("prom_type = 3 and prom_id = $prom_id")->find();
                if(!empty($order_goods))
                {
                    $this->error("该活动有订单参与不能删除!");
                }
		M("goods")->where("prom_id=$prom_id and prom_type=3")->save(array('prom_id'=>0,'prom_type'=>0,'zd'=>0));
		M('prom_goods')->where("id=$prom_id")->delete();
		$this->success('删除活动成功',U('Promotion/prom_goods_list'));
	}



        /**
         * 活动列表
         */
	public function prom_order_list()
	{
		$parse_type = array('0'=>'满额打折','1'=>'满额优惠金额','2'=>'满额送积分','3'=>'满额送优惠券');
		$level = M('user_level')->select();
		if($level){
			foreach ($level as $v){
				$lv[$v['level_id']] = $v['level_name'];
			}
		}
        $count = M('prom_order')->count();
        $Page  = new \Think\Page($count,10);
        $show = $Page->show();
		$res = M('prom_order')->limit($Page->firstRow.','.$Page->listRows)->select();
		if($res){
			foreach ($res as $val){
				if(!empty($val['group']) && !empty($lv)){
					$val['group'] = explode(',', $val['group']);
					foreach ($val['group'] as $v){
						$val['group_name'] .= $lv[$v].',';
					}
				}
				$val['state'] = empty($val['status']) ? '管理员关闭' : '正常';
				if($val['end_time']<time()){
					$val['state'] = '已结束';
				}
				$prom_list[] = $val;
			}
		}
        $this->assign('page',$show);// 赋值分页输出
        $this->assign("parse_type",$parse_type);
		$this->assign('prom_list',$prom_list);
		$this->display();
	}

	public function prom_order_info(){
		$this->assign('min_date',date('Y-m-d'));
		$level = M('user_level')->select();
		$this->assign('level',$level);
		$prom_id = I('id');
		$info['start_time'] = date('Y-m-d');
		$info['end_time'] = date('Y-m-d',time()+3600*24*60);
		if($prom_id>0){
			$info = M('prom_order')->where("id=$prom_id")->find();
			$info['start_time'] = date('Y-m-d',$info['start_time']);
			$info['end_time'] = date('Y-m-d',$info['end_time']);
		}
		$this->assign('info',$info);
		$this->assign('min_date',date('Y-m-d'));
		$this->initEditor();
		$this->display();
	}

	public function prom_order_save(){
		$prom_id = I('id');
		$data = I('post.');
		$data['start_time'] = strtotime($data['start_time']);
		$data['end_time'] = strtotime($data['end_time']);
		$data['group'] = implode(',', $data['group']);
		if($prom_id){
			M('prom_order')->where("id=$prom_id")->save($data);
			adminLog("管理员修改了商品促销 ".I('name'));
		}else{
			M('prom_order')->add($data);
			adminLog("管理员添加了商品促销 ".I('name'));
		}
		$this->success('编辑促销活动成功',U('Promotion/prom_order_list'));
	}

	public function prom_order_del()
	{
		$prom_id = I('id');
                $order = M('order')->where("order_prom_id = $prom_id")->find();
                if(!empty($order))
                {
                    $this->error("该活动有订单参与不能删除!");
                }

		M('prom_order')->where("id=$prom_id")->delete();
		$this->success('删除活动成功',U('Promotion/prom_order_list'));
	}

    public function group_buy_list(){
    	$Ad =  M('group_buy');
    	$p = I('p',1);

    	$count = $Ad->count();
    	$Page = new \Think\Page($count,10);
    	$res = $Ad->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
    	if($res){
    		foreach ($res as $val){
    			$val['start_time'] = date('Y-m-d',$val['start_time']);
    			$val['end_time'] = date('Y-m-d',$val['end_time']);
    			$list[] = $val;
    		}
    	}
    	$this->assign('list',$list);
    	$this->assign('state',array('审核中','正常','未通过','管理员关闭'));
    	$show = $Page->show();
    	$this->assign('page',$show);
    	$this->display();
    }

    public function group_buy(){
    	$act = I('GET.act','add');
    	$groupbuy_id = I('get.id');
    	$group_info = array();
    	$group_info['start_time'] = date('Y-m-d');
    	$group_info['end_time'] = date('Y-m-d',time()+3600*365);
    	if($groupbuy_id){
    		$group_info = D('group_buy')->where('id='.$groupbuy_id)->find();
    		$group_info['start_time'] = date('Y-m-d',$group_info['start_time']);
    		$group_info['end_time'] = date('Y-m-d',$group_info['end_time']);
    		$act = 'edit';
    	}
    	$this->assign('min_date',date('Y-m-d'));
    	$this->assign('info',$group_info);
    	$this->assign('act',$act);
    	$this->display();
    }
    public function dget_goods(){
        $prom_id = I('id');
    
        // !empty(I('keywords')) ? $where=" and goods_name like '%".I('keywords')."%'" : $where="";、
        // $count = M('goods')->where("prom_id=$prom_id ".$where)->count();
        $prom_list = M('prom_goods')->where(['id'=>$prom_id])->find();
       
        $count = 0;
        $ids = '';
        if($prom_list['goods_key']){
            $prom_list['goods_key'] = json_decode($prom_list['goods_key'],true);
            $ids = implode(',',$prom_list['goods_key']);
            $count = M('spec_goods_price p')
            ->join('ty_goods g on g.goods_id = p.goods_id','left')
            ->where(['key'=>['in',$ids]])
            ->count();
        }
        
        
        $Page  = new \Think\Page($count,10);
        $goodsList = M('spec_goods_price p')
            ->field('p.*,g.goods_name')
            ->join('ty_goods g on g.goods_id = p.goods_id','left')
            ->where(['key'=>['in',$ids]])
            ->order('p.goods_id DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
            foreach ($goodsList as $k=>$v){
                $goodsList[$k]['zhekou_price'] = $v['price']*$prom_list['expression']/100;
                $goodsList[$k]['shop_price'] = $v['price'];
            }
        $show = $Page->show();
        $this->assign('page',$show);
        $this->assign('goodsList',$goodsList);
        $this->display('get_goods');
    }
    public function groupbuyHandle(){
    	$data = I('post.');
    	if($data['act'] == 'del'){
    		$r = M('group_buy')->where(array('id'=>$data['id']))->delete();
    		M('goods')->where(array('prom_type'=>2,'prom_id'=>$data['id']))->save(array('prom_id'=>0,'prom_type'=>0));
    		if($r){
    			exit(json_encode(1));
    		}else{
    			exit(json_encode('删除失败'));
    		}
    	}

    	$data['groupbuy_intro'] = htmlspecialchars(stripslashes($_POST['groupbuy_intro']));
    	$data['start_time'] = strtotime($data['start_time']);
    	$data['end_time'] = strtotime($data['end_time']);

    	if($data['act'] == 'add'){
    		$r = M('group_buy')->add($data);
    		M('goods')->where("goods_id=".$data['goods_id'])->save(array('prom_id'=>$r,'prom_type'=>2));
    	}
    	if($data['act'] == 'edit'){
    		$r = M('group_buy')->where('id='.$data['id'])->save($data);
    		M('goods')->where("prom_type=2 and prom_id=".$data['id'])->save(array('prom_id'=>0,'prom_type'=>0));
    		M('goods')->where("goods_id=".$data['goods_id'])->save(array('prom_id'=>$r,'prom_type'=>2));
    	}
    	if($r){
    		$this->success("操作成功",U('Admin/Promotion/group_buy_list'));
    	}else{
    		$this->error("操作失败",U('Admin/Promotion/group_buy_list'));
    	}
    }

    public function get_goods(){
    	$prom_id = I('id');
     
        // !empty(I('keywords')) ? $where=" and goods_name like '%".I('keywords')."%'" : $where="";、
        // $count = M('goods')->where("prom_id=$prom_id ".$where)->count();
        $prom_list = M('prom_goods')->where(['id'=>$prom_id])->find();
       
        $count = 0;
        $ids = '';
        if($prom_list['goods_key']){
            $prom_list['goods_key'] = json_decode($prom_list['goods_key'],true);
            $ids = implode(',',$prom_list['goods_key']);
            $count = M('spec_goods_price p')
            ->join('ty_goods g on g.goods_id = p.goods_id','left')
            ->where(['key'=>['in',$ids]])
            ->count();
        }
        
        
        $Page  = new \Think\Page($count,10);
        $goodsList = M('spec_goods_price p')
            ->field('p.*,g.goods_name')
            ->join('ty_goods g on g.goods_id = p.goods_id','left')
            ->where(['key'=>['in',$ids]])
            ->order('p.goods_id DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
            foreach ($goodsList as $k=>$v){
                $goodsList[$k]['zhekou_price'] = $v['price']*$prom_list['expression']/100;
                $goodsList[$k]['shop_price'] = $v['price'];
            }
        $show = $Page->show();
        $this->assign('page',$show);
        $this->assign('goodsList',$goodsList);
        $this->display();
    }

    public function search_goods(){
    	$GoodsLogic = new \Admin\Logic\GoodsLogic;
    	$brandList = $GoodsLogic->getSortBrands();
    	$this->assign('brandList',$brandList);
    	$categoryList = $GoodsLogic->getSortCategory();
    	$this->assign('categoryList',$categoryList);

    	$goods_id = I('goods_id');
    	$where = ' is_on_sale = 1 and prom_type=0 and store_count>0 ';//搜索条件
    	if(!empty($goods_id)){
    		$where .= " and goods_id not in ($goods_id) ";
    	}
    	I('intro')  && $where = "$where and ".I('intro')." = 1";
    	if(I('cat_id')){
    		$this->assign('cat_id',I('cat_id'));
    		$grandson_ids = getCatGrandson(I('cat_id'));
    		$where = " $where  and cat_id in(".  implode(',', $grandson_ids).") "; // 初始化搜索条件
    	}
    	if(I('brand_id')){
    		$this->assign('brand_id',I('brand_id'));
    		$where = "$where and brand_id = ".I('brand_id');
    	}
    	if(!empty($_REQUEST['keywords']))
    	{
    		$this->assign('keywords',I('keywords'));
    		$where = "$where and (goods_name like '%".I('keywords')."%' or keywords like '%".I('keywords')."%')" ;
    	}
    	$count = M('goods')->where($where)->count();
    	$Page  = new \Think\Page($count,10);
    	$goodsList = M('goods')->where($where)->order('goods_id DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
    	$show = $Page->show();//分页显示输出
    	$this->assign('page',$show);//赋值分页输出
    	$this->assign('goodsList',$goodsList);
    	$tpl = I('get.tpl','search_goods');
    	$this->display($tpl);
    }

    //限时抢购
    public function flash_sale(){
    	$condition = array();
    	$model = M('flash_sale');
    	$count = $model->where($condition)->count();
    	$Page  = new \Think\Page($count,10);
    	$show = $Page->show();
    	$prom_list = $model->where($condition)->order("id desc")->limit($Page->firstRow.','.$Page->listRows)->select();
    	$this->assign('state',array('审核中','正常','未通过','管理员关闭'));
    	$this->assign('prom_list',$prom_list);
    	$this->assign('page',$show);// 赋值分页输出
    	$this->display();
    }

    public function flash_sale_info(){
    	if(IS_POST){
    		$data = I('post.');
    		$data['start_time'] = strtotime($data['start_time']);
    		$data['end_time'] = strtotime($data['end_time']);
    		if(empty($data['id'])){
    			$r = M('flash_sale')->add($data);
    			M('goods')->where("goods_id=".$data['goods_id'])->save(array('prom_id'=>$r,'prom_type'=>1));
    			adminLog("管理员添加抢购活动 ".$data['name']);
    		}else{
    			$r = M('flash_sale')->where("id=".$data['id'])->save($data);
    			M('goods')->where("prom_type=1 and prom_id=".$data['id'])->save(array('prom_id'=>0,'prom_type'=>0));
    			M('goods')->where("goods_id=".$data['goods_id'])->save(array('prom_id'=>$data['id'],'prom_type'=>1));
    		}
    		if($r){
    			$this->success('编辑抢购活动成功',U('Promotion/flash_sale'));
    			exit;
    		}else{
    			$this->error('编辑抢购活动失败',U('Promotion/flash_sale'));
    		}
    	}
    	$id = I('id');
    	$info['start_time'] = date('Y-m-d');
    	$info['end_time'] = date('Y-m-d',time()+3600*24*60);
    	if($id>0){
    		$info = M('flash_sale')->where("id=$id")->find();
    		$info['start_time'] = date('Y-m-d',$info['start_time']);
    		$info['end_time'] = date('Y-m-d',$info['end_time']);
    	}
    	$this->assign('info',$info);
    	$this->assign('min_date',date('Y-m-d'));
    	$this->display();
    }

    public function flash_sale_del(){
    	$id = I('del_id');
    	if($id){
    		M('flash_sale')->where("id=$id")->delete();
    		M('goods')->where("prom_type=1 and prom_id=$id")->save(array('prom_id'=>0,'prom_type'=>0));
    		 exit(json_encode(1));
    	}else{
    		 exit(json_encode(0));
    	}
    }

    public function activity_handle(){
    	$tab = I('tab');
    	$id = I('id');
    	$status = I('status');
    	if(M($tab)->where(array('id'=>$id))->save(array('status'=>$status))){
    		exit(json_encode(1));
    	}else{
    		exit(json_encode(0));
    	}
    }

    /*
    * 每日签到
    */
    public function sign_in()
    {
        $model = M('sign_in');
        if(IS_POST){

            $data = I('post.');
            unset($data['__hash__']);

            if(empty($data['sign_points'])){
                $this->error('每日签到积分不能为空');
            }
            $data['sign']=json_encode($data['sign']);
            $data['score']=json_encode($data['score']);

            if(empty($data['id'])){

                $row =$model->add($data);
            }else{
                $row =$model->where(array('id'=>$data['id']))->save($data);
            }
            if(!$row)
                $this->error('添加失败');
            $this->success('添加成功',U('Promotion/sign_in'));
            exit;
        }
         $res =   $model->select();
        $res[0]['sign']=json_decode($res[0]['sign']);
        $res[0]['score']=json_decode($res[0]['score']);
        $sign1 = array_combine($res[0]['sign'],$res[0]['score']);
        $res[0]['signs']=$sign1;

        $this->assign("sign", $res[0]);
        $this->display();
    }

    private function initEditor()
    {
    	$this->assign("URL_upload", U('Admin/Ueditor/imageUp',array('savepath'=>'promotion')));
    	$this->assign("URL_fileUp", U('Admin/Ueditor/fileUp',array('savepath'=>'promotion')));
    	$this->assign("URL_scrawlUp", U('Admin/Ueditor/scrawlUp',array('savepath'=>'promotion')));
    	$this->assign("URL_getRemoteImage", U('Admin/Ueditor/getRemoteImage',array('savepath'=>'promotion')));
    	$this->assign("URL_imageManager", U('Admin/Ueditor/imageManager',array('savepath'=>'promotion')));
    	$this->assign("URL_imageUp", U('Admin/Ueditor/imageUp',array('savepath'=>'promotion')));
    	$this->assign("URL_getMovie", U('Admin/Ueditor/getMovie',array('savepath'=>'promotion')));
    	$this->assign("URL_Home", "");
    }
 /**
	 *店铺满赠活动列表
	 */
	 public function prom_full_list(){
	     $timegap = I('timegap');
		if($timegap){
			$gap = explode(' - ', $timegap);
			$begin = strtotime($gap[0]);
			$end = strtotime($gap[1]);
		}else{
            $begin2 = date('Y-m-d 00:00',(time()-30*60*60*24));//30天前
            $end2 = date('Y-m-d 23:59',strtotime('+1 days'));
            $begin = strtotime($begin2);
            $end = strtotime($end2);
        }
        $this->assign('timegap',$begin2.' - '.$end2);
	     $this->display();
	 }
	 
	 
    public function ajaxprom_full_list(){
	     
	    $count = M('goods_full')->where('store_id is NULL')->count();
	    
	    $Page  = new AjaxPage($count,20);
        $show = $Page->show();
        $list = M('goods_full')->where('store_id is NULL')->limit($Page->firstRow.','.$Page->listRows)->order('id desc')->select();
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('prom_list',$list);// 赋值分页输出
	    $this->display();
	 }
	 
	 public function prom_full_info(){
	     $id = I('id');
	     $info = M('goods_full')->where(['id'=>$id])->find();
	     if(!empty($info['full_gift'])){
	         $info['full_gift'] = json_decode($info['full_gift'],true);
	     }
	     if(!empty($info)){
	         $info['end_time'] = date('Y-m-d H:i',$info['end_time']);
	        $info['start_time'] = date('Y-m-d H:i',$info['start_time']);
	     }
	     
	     $min_date = date('Y-m-d');
	     $this->assign('info',$info);
	     $this->assign('min_date',$min_date);
	     $this->display();
	 }
	 public function prom_full_save(){
	     
	     if(IS_POST){
	       
	         $param = I('');
	         $sendData = [];
	         $sendData['name'] = $param['name'];
	         $sendData['start_time'] = strtotime($param['start_time']);
	         $sendData['end_time'] = strtotime($param['end_time'])+86399;
	      
	         $Data = [];
    	    foreach ($param['full_price'] as $k=>$v){
    	        $Data[$k]['price'] = $v;
    	        $Data[$k]['gift'] = $param['full_gift'][$k];
    	    }
    	    if(empty($Data)){
    	        $this->success('送礼不能为空');
                die;
    	    }
    	    $sendData['full_gift'] = json_encode($Data);
    	    if($sendData['end_time'] < $sendData['start_time']){
    	        $this->success('结束时间不能小于开始时间');
                die;
    	    }
    	    $sendData['type'] = 3;
    	    //检测区间是否存在其他活动
    	   // $info = M('goods_full')->where("store_id = $store_id and start_time >= $start and end_time <=$end")->find();
    	   //  dump($sendData);
    	   //  die;
	         if(!empty($param['id'])){//修改
	            $info = M('goods_full')->where("id=".$param['id'])->find();
	            if($info['end_time'] < time()){
	                 $this->success('已经结束，无法修改');
	                 die;
	            }
	            $info = M('goods_full')->where(['id'=>$param['id']])->save($sendData);
	            $this->success('操作成功',U('Promotion/prom_full_info',['id'=>$param['id']]));
	         }else{//新增
	            $sendData['add_time'] = time();
	            $model = D('goods_full');
	            $info = $model->add($sendData);
	          
	            $this->success('操作成功',U('Promotion/prom_full_info',['id'=>$info]));
	         }
	         
	     }
	 }
	
	public function daochufull(){
	    $id = I('id');
	    $info = M('goods_full')->where("id=".$id)->find();
	    $full = json_decode($info['full_gift'],true);
	    usort($full, function ($a, $b) {
            return $a['price'] - $b['price'];
        });
	    $begin = $info['start_time'];
	    $end = $info['end_time'];
	    
		$where .= " a.order_status in(0,1,2,4) ";
        $whereb="a.addtime>$begin and a.addtime<$end and b.is_lock=0";
		$sql = "select a.add_time,count(a.order_id) as order_num,sum(a.total_amount+yijia_heji) as amount,a.user_id,b.mobile,b.company,b.nickname,b.user_id,b.biaoshi,b.biaoshi_xian,b.company_address from __PREFIX__order as a left join __PREFIX__users as b on a.user_id = b.user_id where a.add_time>$begin and a.add_time<$end and $where group by a.user_id order by amount DESC";
    	$orderList = D()->query($sql);
     
    	$strTable ='<table width="500" border="1">';
    	$strTable .= '<tr>';
    	$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">用户ID</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="100">排行</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">礼物</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">客户名</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">线路</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">客户地址</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">订单数</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">购物金额</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">退货金额</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">实际金额</td>';
    	$strTable .= '</tr>';
    	foreach($orderList as $k=>$val){
    	    //把禁止活动的剔除出去
    	    $pgoods = M('order_goods g')
    	    ->join('ty_order o on o.order_id = g.order_id','left')
    	   // ->where(['full_status'=>1,'user_id'=>$val['user_id'],'store_id'=>$store_id])
    	    ->where("g.full_status = 0 and o.user_id = ".$val['user_id']." and o.add_time>$begin and o.add_time<$end")
    	    ->sum('(member_goods_price+yijia)*goods_num');
    	      if(empty($pgoods)){
    	          $pgoods = 0;
    	      }
    	    
    	    
           
            $userInfo = M('users')->where(['user_id'=>$val['user_id']])->find();
            $return_goods_price = 0;
            if(!empty($userInfo)){
                $tuikuan2=M('return_goods a')
                ->field("a.member_goods_price,a.goods_num")
                ->join('ty_users b on a.user_id=b.user_id')
                ->where($whereb.' and a.user_id = '.$val['user_id'])
                ->select();
              
                if(count($tuikuan2) > 0){
                    foreach ($tuikuan2 as $key => $value){
                        $return_goods_price += ($value['member_goods_price']*$value['goods_num']);
                    }
                }
            }
            
                
           $val['return_goods_price'] = $return_goods_price;
           $shiji = geshi($pgoods-$val['return_goods_price']);
           $orderList[$k]['gift'] = '';
            foreach($full as $key=>$v){
                if($shiji > $v['price']){
                    $val['gift'] = $v['gift'];
                }
            }
     
    		$strTable .= '<tr>';
    		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['user_id'].'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.($k+1).' </td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['gift'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['nickname'].'（'.$val['company'].'）'.' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['biaoshi_xian'].'</td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['company_address'].'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['order_num'].'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$pgoods.'</td>';
    // 		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['amount'].'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['return_goods_price'].'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$shiji.'</td>';
    		$strTable .= '</tr>';
    	}
    
    	$strTable .='</table>';
    	unset($orderList);
    	downloadExcel($strTable,'order');
    	exit();
	}
	
public function prom_goods_id_info()
	{
	    
	   
        $goods_ids = I('goods_ids');
        $goods_id = I('goods_id');
		$level = M('user_level')->select();
		$this->assign('level',$level);
		$prom_id = I('id');
		$info['start_time'] = date('Y-m-d H:i');
		$info['end_time'] = date('Y-m-d H:i',time()+3600*60*24);
		if($goods_id > 0){
            $goods = M('goods')->where(['goods_id'=>$goods_id])->find();
			$info = M('prom_goods')->where("pgoods_id=$goods_id")->find();
		 
			if(!empty($info)){
			    $info['start_time'] = date('Y-m-d H:i:s',$info['start_time']);
			    $info['end_time'] = date('Y-m-d H:i:s',$info['end_time']);
			}
		    if($info['goods_key']){
				$goods_key=\json_decode($info['goods_key']);
				foreach($goods_key as $key=>$v){
					$prom_goods[$key]= M('spec_goods_price a')->field('a.key,a.key_name,a.price,b.*')->join('ty_goods b on a.goods_id=b.goods_id','LEFT')->where('a.key="'.$v.'"')->find();
					$prom_goods[$key]['shop_price']=$prom_goods[$key]['price'];
				}
			}
            $this->assign('goods',$goods);
			$this->assign('prom_goods',$prom_goods);
		}
		if(!empty($goods_ids)){
		    $store_ids = M('goods')->where(['goods_id'=>['in',$goods_ids]])->group('store_id')->select();
		  
		    if(count($store_ids) > 1){
		        $this->error('存在不同商家');
		        die;
		    }
		    $goods = M('goods')->where(['goods_id'=>['in',$goods_ids]])->select();
		    $goods_name = '';
		    foreach ($goods as $k=>$v){
		        $goods_name .= $v['goods_name'].',';
		    }
		   
		    $this->assign('goods_ids',$goods_ids);
		    $this->assign('goods_name',$goods_name);
		}
		
		$this->assign('info',$info);
		$this->assign('min_date',date('Y-m-d H:i'));
		$this->initEditor();
		$this->display();
	}
	 public function search_goods_id(){
    	$GoodsLogic = new \Admin\Logic\GoodsLogic;
    	$brandList = $GoodsLogic->getSortBrands();
    	$this->assign('brandList',$brandList);
    	$categoryList = $GoodsLogic->getSortCategory();
    	$this->assign('categoryList',$categoryList);
    	
        /*
         * 可以用这两条sql 语句代替 
         * select group_concat(concat( class_1,',',class_2,',',class_3 )) from tp_store_bind_class group by store_id
         * select group_concat(concat_ws( ',',class_1,class_2,class_3 )) from tp_store_bind_class group by store_id         
         */
        // $bind_class_id = array();
        // $store_bind_class = M('store_bind_class')->where("store_id = ".STORE_ID." and state = 1")->select();
        // foreach($store_bind_class as $key => $val)
        // {
        //     $bind_class_id[] = $val['class_1']; 
        //     $bind_class_id[] = $val['class_2']; 
        //     $bind_class_id[] = $val['class_3']; 
        // }
        // $this->assign('bind_class_id',$bind_class_id);
        
    	$goods_id = I('goods_id');
    	$where = ' b.is_on_sale = 1  and a.goods_id ='.$goods_id;//搜索条件and b.prom_type=0 
    // 	if(!empty($goods_id)){
    // 		$where .= " and a.goods_id = $goods_id  ";
    // 	}
    // 	I('intro')  && $where = "$where and ".I('intro')." = 1";
        // $cat_id = I('cat_id');
    // 	if($cat_id){
    // 		$this->assign('cat_id',$cat_id);
    // 		$goods_category = M('goods_category')->where("id = $cat_id")->find();
    // 		$where = " $where  and cat_id{$goods_category['level']} = $cat_id"; // 初始化搜索条件
    // 	}
    // 	if(I('brand_id')){
    // 		$this->assign('brand_id',I('brand_id'));
    // 		$where = "$where and brand_id = ".I('brand_id');
    // 	}
    // 	if(!empty($_REQUEST['keywords']))
    // 	{
    // 		$this->assign('keywords',I('keywords'));
    // 		$where = "$where and (b.goods_name like '%".I('keywords')."%' or b.goods_id like '%".I('keywords')."%' or b.keywords like '%".I('keywords')."%')" ;
    // 	}
    // 	dump($where);
    	$count = M('spec_goods_price a')->field('a.key,a.key_name,b.*')->join('ty_goods b on a.goods_id=b.goods_id','LEFT')->where($where)->count();
    	$Page  = new \Think\Page($count,30);
		
    	$goodsList = M('spec_goods_price a')->field('a.key,a.key_name,a.price,b.*')->join('ty_goods b on a.goods_id=b.goods_id','LEFT')->where($where)->order('goods_id DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
    	$show = $Page->show();//分页显示输出
    	$this->assign('page',$show);//赋值分页输出
    	$this->assign('goodsList',$goodsList);
    	$this->display('search_goods_id');
    }
    public function prom_goods_id_save()
	{
	    $prom_id = I('id');
		$data = I('post.');
	
		$data['start_time'] = strtotime($data['start_time']);
		$data['end_time'] = strtotime($data['end_time'])+86399;
		$data['group'] = implode(',', $data['group']);
        $data['prom_code'] = $data['prom_code'];
        $data['pgoods_id'] = $data['goods_id'];
     
        $store_id = M('goods')->where(['goods_id'=>$data['goods_id']])->getField('store_id');
      
		if($prom_id>0){
		    //检测是否有一致的
		    $info = M('prom_goods')->where("id=$prom_id and store_id=".$store_id.' and pgoods_id='.$data['goods_id'])->find();
		    if(!empty($info['goods_key'])){
		        $info['goods_key'] = json_decode($info['goods_key'],true);
		        $mergedArray = array_merge($info['goods_key'], $data['goods_key']);
                // 去除重复值
                $uniqueArray = array_unique($mergedArray);
		    }
		    
	    	$data['goods_key'] = \json_encode($uniqueArray);
	    	$data['name'] = date('Ymd').'活动特价';
			M('prom_goods')->where("id=$prom_id and store_id=".$store_id.' and pgoods_id='.$data['goods_id'])->save($data);
			$last_id = $prom_id;
// 			sellerLog("管理员修改了商品促销 ".I('name'));
		}else{
		    if(!empty($data['goods_ids'])){
		       $store_id = M('goods')->where(['goods_id'=>['in',$data['goods_ids']]])->getField('store_id');
		        $arr_goods_ids = explode(',',$data['goods_ids']);
		      //  dump($arr_goods_ids);
		      //  dump($data);
		      //  die;
		        foreach ($arr_goods_ids as $k=>$v){
		        
		            //获取两个产品所有的key
    		        $spec_key = M('spec_goods_price')->where(['goods_id'=>$v])->select();
    		        
    		        $goods_key = [];
    		        if(!empty($spec_key)){
    		            foreach ($spec_key as $k=>$vs){
        		            $goods_key[] = $vs['key'];
        		        }
    		        }
    		      
    		        $info = M('prom_goods')->where("store_id=".$store_id.' and pgoods_id='.$v)->find();
    		        $data['pgoods_id'] = $v;
    		        $data['id'] = $info['id'];
    		        $data['goods_key'] = \json_encode($goods_key);
        			$data['store_id'] = $store_id;
        			$data['name'] = date('Ymd').'活动特价';
        		  
        		      //  dump($data);
        		      //  die;
    		        if(!empty($info)){
    		            $last_id = M('prom_goods')->where("store_id=".$store_id.' and pgoods_id='.$v)->save($data);
    		            M("goods")->where(['goods_id'=>$v])->save(array('prom_id'=>$info['id'],'prom_type'=>I('type'),'zd'=>0));
    		           
    		        }else{
    		          //  $goods_id = $data['goods_id'];
    		          //  unset($data['id']);
    		          //  unset($data['__hash__']);
    		          //  unset($data['group']);
    		          //  unset($data['prom_code']);
    		          //  unset($data['goods_ids']);
    		          //  unset($data['goods_id']);
    		            
    		          //  dump($data);
    		            
    		            $model = M('prom_goods');
    		            $row = $model->create($data);
                        $model->add();
                        // dump($row['id']);
                        
    		          //  $last_id = $row['id'];
    		          $prom_id_goods = M('prom_goods')->where(['pgoods_id'=>$v])->getField('id');
    		            M("goods")->where(['goods_id'=>$v])->save(array('prom_id'=>$prom_id_goods,'prom_type'=>I('type'),'zd'=>0));
    		          //  die;
    		        }
		        }
		        $this->success('编辑促销活动成功',U('Promotion/prom_goods'));
		        
		        exit;
		    }else{
		        $data['goods_key'] = \json_encode($data['goods_key']);
    			$data['store_id'] = $store_id;
    			$last_id = M('prom_goods')->add($data);
		    }
		    
// 			sellerLog("管理员添加了商品促销 ".I('name'));
		}
	
		if($data['goods_id'] > 0){

			if($prom_id>0){
				M("goods")->where(['goods_id'=>$data['goods_id']])->save(array('prom_id'=>0,'prom_type'=>0,'zd'=>0));
			}
			M("goods")->where(['goods_id'=>$data['goods_id']])->save(array('prom_id'=>$last_id,'prom_type'=>$data['type'],'zd'=>0));
		}
		cart_price();
		$this->success('编辑促销活动成功');
	}
	 /*
    商品单个促销
    */
    public function prom_goods(){
        $GoodsLogic = new GoodsLogic();
        $brandList = $GoodsLogic->getSortBrands();
        $categoryList = $GoodsLogic->getSortCategory();
		//获取一级分类
		$goods_category = M('goods_category')->where(['level'=>1])->select();
		//获取二级分类
        $goods_category2 = M('goods_category')->where(['level'=>2])->select();
        //获取三级分类
        $goods_category3 = M('goods_category')->where(['level'=>3])->select();
		$this->assign('goods_category',$goods_category);
		$this->assign('goods_category2',$goods_category2);
		$this->assign('goods_category3',$goods_category3);
        $this->assign('categoryList',$categoryList);
        $this->assign('brandList',$brandList);
        $this->display();
    }
    
    public function ajaxprom_goods(){
         $where = ' 1 = 1 '; // 搜索条件
        $parse_type = array('0'=>'单品秒杀','1'=>'降价促销','2'=>'一口价促销','3'=>'买就赠优惠券','4'=>'全店打折','5'=>'每日秒杀');
        // I('fenbu_id') && $where = "$where and a.fenbu_id=".I('fenbu_id');
        I('intro')    && $where = "$where and ".I('intro')." = 1" ;
        I('brand_id') && $where = "$where and brand_id = ".I('brand_id') ;
        (I('goods_state') !== '') && $where = "$where and goods_state = ".I('goods_state') ;
        $cat_id = I('cat_id');
        $cat_id1 = I('cat_id1');
        $cat_id2 = I('cat_id2');
        $cat_id3 = I('cat_id3');
        $cat_key = I('cat_key');
        $prom_status = I('prom_status');
        $brand_name = I('brand_name');
        if(!empty($cat_id1)){
            $where = "$where and a.cat_id1 = ".$cat_id1 ;
        }
        if(!empty($cat_id2)){
            $where = "$where and a.cat_id2 = ".$cat_id2 ;
        }
        if(!empty($cat_id3)){
            $where = "$where and a.cat_id3 = ".$cat_id3 ;
        }
        if(!empty($cat_key)){
            $categoryids = M('goods_category')->where(['level'=>3,'name'=>$cat_key])->find();
            // dump($categoryids);
            if(!empty($categoryids)){
                $where = "$where and a.cat_id3 = ".$categoryids['id'] ;
            }
        }
        if(!empty($prom_status)){
            $time = time();
            if($prom_status == 1){
                $where .=' and a.prom_id != 0 and ( p.start_time <='.$time.' and p.end_time >='.$time.')';
            }
            if($prom_status == 2){
                 $where .=' and a.prom_id = 0';
            }
        }
        
        if($brand_name)
		{
		    $where = "$where and name like '%$brand_name%'" ;
		}
        // 关键词搜索               
        $key_word = I('key_word') ? trim(I('key_word')) : '';
		$dp_word = I('dp_word') ? trim(I('dp_word')) : '';
        if($key_word)
        {
            $where = "$where and (goods_name like '%$key_word%' or goods_sn like '%$key_word%' or goods_id='$key_word')" ;
        }

		if($dp_word)
		{
		    $where = "$where and (store_name like '%$dp_word%')" ;
		}
		
          
        $where .= " and  is_delete=0 and goods_state=1 and is_on_sale =1";
            // dump($where);
        $model = M('Goods');
        $count = $model
		->alias('a')
		->field('a.*,b.store_name')
		->join('ty_store b ON b.store_id= a.store_id')
		->join('ty_prom_goods p ON p.pgoods_id= a.goods_id','left')
		->where($where)
		->group('a.goods_id')
		->select();
		
        $Page  = new AjaxPage(count($count),20);
        $show = $Page->show();
        $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
// 		dump($where);
        $goodsList = $model
		->alias('a')
		->field('a.*,b.store_name,p.start_time,p.end_time,p.expression')
		->join('ty_store b ON b.store_id= a.store_id')
		->join('ty_prom_goods p ON p.pgoods_id= a.goods_id','left')
		->where($where)
		->order($order_str)
		->group('a.goods_id')
		->limit($Page->firstRow.','.$Page->listRows)->select();
	   // dump($goodsList);
		foreach($goodsList as $key=>&$v){
			$v["goods_type_name"]= M("goods_category")->where(['id'=>$v['cat_id3']])->getField('name');
			$v['zhuangtai']=M('store_msg')->where('goods_id='.$v['goods_id'])->order('sm_id desc')->getField('content');
             $goodsList[$key]['original_img'] = C('MYOSS')['url2'].$v['original_img'];
             if(!empty($v['start_time']) && !empty($v['end_time'])){
                 $goodsList[$key]['start_time'] = date('Y-m-d H:i:s',$v['start_time']).'-'.date('Y-m-d H:i:s',$v['end_time']);
                 $goodsList[$key]['time_status'] = 1;
             }else{
                 $goodsList[$key]['start_time'] = '还没设置';
                 $goodsList[$key]['time_status'] = 0;
             }
            //  if(!empty($v['end_time'])){
            //      $goodsList[$key]['end_time'] = date('Y-m-d H:i:s',$v['end_time']);
            //  }else{
            //      $goodsList[$key]['end_time'] = '还没设置';
            //  }
		}
        // dump($parse_type);
        $catList = D('goods_category')->select();
        $catList = convert_arr_key($catList, 'id');
        $goods_state = C('goods_state');
        $this->assign('catList',$catList);
        $this->assign('goodsList',$goodsList);
        $this->assign('goods_state',$goods_state);
        $this->assign('parse_type',$parse_type);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();       
    }
    
    
    /*
    *取消产品活动
    */
    public function quxiaoprom_goods(){
        $data = I('');
        $prom_goods = M('prom_goods')->where(['pgoods_id'=>$data['goods_id']])->find();
        if(empty($prom_goods)){
            $this->error('删除失败');
            die;
        }
        M("goods")->where(['goods_id'=>$data['goods_id']])->save(array('prom_id'=>0,'prom_type'=>0,'zd'=>0));
        M('prom_goods')->where(['pgoods_id'=>$data['goods_id']])->delete();
       
       $this->success("操作成功!");
       
    }
    
}